/*
 *
 * Purpose:
 * Rely on: jquery.tools.js
 *
 **/

$.tools.validator.addEffect('integerated_validator_errors', function(errors, event){
    var wall = $(this.getConf().container).fadeOut(200, function(){
        $(this).fadeIn()
        });
    wall.empty();
    $.each(errors, function(index, error) {
        error_tag = ''
        if( error.input.attr("localize_name") != undefined ){
            error_tag = error.input.attr("localize_name");
        }
        wall.append( "<p><strong>" + error_tag + "</strong> " +error.messages[0] + "</p>" );
    });
},function(){});


// supply the language
$.tools.validator.localize("zh_cn", {
    ':email'  	: '邮件地址格式不正确!',
    ':url' 		: '无效的 URL',
    '[max]'	 	: '最大长度为 $1',
    '[min]'		: '最小长度为$1',
    '[required]'	: '为必填项!'
});

$.tools.validator.fn("[data-equals]", "Value not equal with the $1 field", function(input) {
    var name = input.attr("data-equals"),
    field = this.getInputs().filter("[name=user[" + name + "]]");
    return input.val() == field.val() ? true :{
        zh_cn: "两次密码不匹配!"
    };

});


$.tools.validator.fn("[minlength]", function(input, value) {
    var min = input.attr("minlength");

    return value.length >= min ? true : {
        zh_cn: "请输入至少 " +min+ " 个字符!" + (min > 1 ? "" : "")
    };
});

$.tools.validator.fn("[maxlength]", function(input, value) {
    var max = input.attr("maxlength");
    return value.length <= max ? true : {
        zh_cn: "请输入至多 " +max+ " 个字符!"
    };
});

$.tools.validator.fn("[type=qq]", "QQ格式为5位及以上数字!", function(input, value) {
    return /^\d{5+}$/.test(value) ? true : {
        zh_cn: "QQ格式为5位及以上数字!"
    };
});

$.tools.validator.fn("[type=msn]", "Msn格式为邮件地址!", function(input, value) {
    return /^\d{5+}$/.test(value) ? true : {
        zh_cn: "Msn格式为邮件地址!"
    };
});

$.tools.validator.fn("[type=gtalk]", "Gtalk格式为邮件地址!", function(input, value) {
    return /^\d{5,15}$/.test(value) ? true : {
        zh_cn: "Gtalk格式为邮件地址!"
    };
});

$.tools.dateinput.localize("zh_cn",  {
    months:         '一月,二月,三月,四月, 五月,六月,七月,八月,九月,十月,十一月,十二月',
    shortMonths:   '一,二,三,四,五,六,七,八,九,十,十一,十二',
    days:          '星期一,星期二,星期三,星期四,星期五,星期六,星期日',
    shortDays:     '一,二,三,四,五,六,日'
 });

/*
 *
 * Purpose: 
 * Rely on: jquery.tools.js
 *
 **/
 //抛出异常
;(function(){
    $.fn.throwCaution = function(opt){
        var defaultOpt = {
            before:null,
            html:''
        }
        opt = $.extend(true,{},defaultOpt,opt);
            return this.each(function(i,e){
            var cautionsContainer = $('<div class="show_cautions"></div>');
            var cautionsIcon = $('<div class="fl caution_icon">&nbsp;</div>');
            var cautionsClose = $('<div class="fr caution_close">close</div>').click(function(){
                    $(this).closest('.show_cautions').remove();
                });
            var html  = $('<span>'+opt.html+'</span>')
            cautionsIcon.appendTo(cautionsContainer);
            cautionsClose.appendTo(cautionsContainer);
            html.appendTo(cautionsContainer);
            opt.before = opt.before || $(this);
            cautionsContainer.insertBefore(opt.before);   
        });
    }
})(jQuery);
//ie last-child support
function supportIE(){
    if($.browser.msie){
        $('table.new_silver_table tr th:last-child,table.new_silver_table tr td:last-child').css({'border-right':'none'});
    }
  
} 
// cookies
function cookie_get(k) {
    var h = document.cookie.split("; ");
    g = h.length;
    f = [];
    for (var j = 0; j < g; j++) {
        f = h[j].split("=");
        if (k === f[0]) {
            return unescape(f[1]);
        }
    }
    return null;
}

function cookie_set(f, g,del) {
    var h = new Date();
    if(!del){
         h.setDate(h.getDate() + 1);
     }else{
        h.setDate(h.getDate() - 10);
     }
    document.cookie = f + "=" + escape(g) + "; expires=" + h.toGMTString()+"; path=/";
}

// show & hide tips
$(function(){
    $('.cookie_tips').each(function(){
        var tip_id = $(this).attr('id');
       if (!(cookie_get('show_tips#'+tip_id) == 'true')) {
            $(this).show();
            $('.click_tip_show').hide();
       }else{
             $(this).hide();
            $('.click_tip_show').show();
       }
    });
    $(".cookie_tips .event_tip_close").click(function(){
        var tip_box = $(this).closest(".cookie_tips").hide();
        $(this).closest('.cookie_tips').prev('.statsBodyHeader').find('.click_tip_show').css('display', 'inline-block');
        var tip_id = tip_box.attr('id');
        cookie_set('show_tips#'+tip_id, true);
    });
    $('.click_tip_show ').click(function(){
        var tip_id=$(this).parents('div').next('.cookie_tips').show().attr('id');
        cookie_set('show_tips#'+tip_id, false,true);
        $(this).hide();
    });
});

// region url ---------------------
function trimUrl(url)
{
if(url != null && url.length > 1)
{
  var temp = url[url.length - 1] == '#' ? url.substring(0,url.length - 1) : url;
  var pos = temp.indexOf("?",0);
  if (pos!=-1)
  {
    temp = url.substring(0,pos)
  }
  return temp[temp.length - 1] == '/' ? temp.substring(0,temp.length - 1) : temp;
}
else
  return url;
}
// region url end -------------------


//
function getQueryString(name)
{
    if(location.href.indexOf("?")==-1 || location.href.indexOf(name+'=')==-1)
    {
        return '';
    }
    var queryString = location.href.substring(location.href.indexOf("?")+1);
    var parameters = queryString.split("&");
    var pos, paraName, paraValue;
    for(var i=0; i<parameters.length; i++)
    {
        pos = parameters[i].indexOf('=');
        if(pos == -1) {
            continue;
        }
        paraName = parameters[i].substring(0, pos);
        paraValue = parameters[i].substring(pos + 1);
        if(paraName == name)
        {
            return unescape(paraValue.replace(/\+/g, " "));
        }
    }
    return '';
}

 
 // tab click actions
var _gel = function(id){return document.getElementById(id)}
function changeTab(n,len,tab,con,cln,sel, callback, callbackParams) {
    //callback = callback ||{};
    for (var i = 0;i < len; i++) {
        try {
            if (n == i) {
                _gel(tab + i).className = cln + ' ' + sel;
                _gel(con + i).style.display = 'block';
            } else {
                _gel(tab + i).className = cln;
                _gel(con + i).style.display = 'none';
            }
        } catch(e) {

        }
    }
    
    if(callback != undefined){
        callback.apply(this, callbackParams||[]);
    }
}

// show number bars
function createNumBar(tabcon,num,numbar,total, numbar_default) {
    var len = _gel(tabcon).getElementsByTagName('tr').length - 1;
    if(len <= 0 ) {return;}
    var sumValue = 0;
    var valueArr = [];
    for(var i=0; i < len ; i ++) {
        sumValue += _gel(num + i).innerHTML-0;
        valueArr.push(_gel(num + i).innerHTML-0);
    }
    if( total != undefined ){
        sumValue = total;
    }
    var maxValue = valueArr.sort( function(a,b){return a-b;})[valueArr.length-1];
    var boxW = _gel(numbar + '0').offsetWidth - 60;
    if (boxW < 0){
      boxW = numbar_default;
    }

    for(var i=0; i < len ; i ++) {
        var divBox = document.createElement('div');
        divBox.style.cssText = 'position:relative;';
        var div = document.createElement('div');
        var p = (_gel(num + i).innerHTML-0) * boxW / maxValue;
        div.style.backgroundColor = '#7477D5';  // #CACFE0
        div.style.height = 15 + 'px';
        var barWidth = isNaN(p) ? 0 : p;
        div.style.width = barWidth + 'px';
        var divTxt = document.createElement('div');
        divTxt.style.cssText = 'position:absolute;right:0;top:0px;'
        var percentage = ((_gel(num + i).innerHTML-0) / sumValue * 100).toFixed(1);
        percentage = isNaN(percentage)? 0 : percentage;
        divTxt.innerHTML = percentage + '%';
        divBox.appendChild(div);
        divBox.appendChild(divTxt);
        _gel(numbar + i).appendChild(divBox);
    }
}

// selected app change action
function showSelect(app_title) {
    var base_url = window.location.href;
    var url = "apps/" + app_title + "/";
    var redirect_url = base_url.replace(/apps\/([^\/]+\/)/, url);
    redirect_url = redirect_url.replace(/events\/.*/, 'events');
    window.location.href = redirect_url;   
}

// adjust page header background position
function adjust() {
    var h = $(".conleft")[0].offsetHeight;
    var main = document.getElementById("main");
    main.style.minHeight = (h - 5) + "px";
}

// get start date param
function getStartDate(){
  return $("input[name='start_date']:first").val();
}

// get end date parma
function getEndDate(){
  return $("input[name='end_date']:first").val();
}

function getURLParameter(name) {
    return decodeURIComponent((RegExp('[?|&]' + name + '=' + '(.+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}

function setParamAndReload(key, value){
    key = escape(key); value = encodeURIComponent(value);
    var kvp = document.location.search.substr(1).split('&');
    var i = kvp.length; var x;
    while(i--)
    {
        x = kvp[i].split('=');
        if (x[0]==key)
        {
            x[1] = value;
            kvp[i] = x.join('=');
            break;
        }
    }
    if(i<0) {kvp[kvp.length] = [key,value].join('=');}

    //this will reload the page, it's likely better to store this until finished
    document.location.search = kvp.join('&');
}
function getParams(params_div_container, content){
    var params = '';
    var url_params = location.href.split('?')[1];
    if( url_params !== undefined){
        params += url_params.split('#')[0] + "&";
    }
    var ps = params_div_container.find("input.date, select, input[type='hidden']");
    ps.each(function(){
        if( this.name != undefined){
            name = this.name;
            value = $.trim(this.value);
            if( name !== '' && value !== ''){
                params += name + "=" + value + "&";
            }
        }
    });
    if ($('#ipt_set_default').is(':checked')){
      params += "set_default=true&";
    }
    $('#tb_channels input:checked[name="channels[]"]').each(function(){
      params += "channels[]=" + $(this).val() + "&";
    });
    return params + 'type='+ content;
}
function isEmail (s) {
  var isEmail_re       = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
  return String(s).search (isEmail_re) != -1;
}
function formatDate(date) {
  var mm = date.getMonth() + 1;
  var dd = date.getDate();
  var yyyy = date.getFullYear();
  mm = (mm < 10) ? '0' + mm : mm;
  dd = (dd < 10) ? '0' + dd : dd;
  return yyyy + "-" + mm + "-" + dd;
}
// send login log to op
function loginlog(user_id)
{
  var login_date = cookie_get('um_login_date_' + user_id);
  var today_date = new Date().toDateString();
  if(today_date != login_date)
  {
    cookie_set('um_login_date_' + user_id, today_date);
    $.getJSON("http://op.umeng.us/loginlogs/add?userid="+user_id+"&callback=?",function(d){});
  }
}


/*(function($){
	
    $.fn.tzSelect = function(options){
        options = $.extend({
            render : function(option){
                return $('<li>',{
                    html : option.text()
                });
            },
            className : ''
        },options);
		
        return this.each(function(){
			
            // The "this" points to the current select element:
			
            var select = $(this);
			
            var selectBoxContainer = $('<div>',{
                width		: select.outerWidth(),
                className	: 'tzSelect',
                html		: '<div class="selectBox"></div>'
            });
			
            var dropDown;
            if ($(this).find("option").size() > 20) {
                dropDown = $('<ul>',{
                    className:'dropDown f'
                });
            }
            else {
                dropDown = $('<ul>',{
                    className:'dropDown'
                });
            }
            var selectBox = selectBoxContainer.find('.selectBox');
			
            // Looping though the options of the original select element

            if(options.className){
                dropDown.addClass(options.className);
            }
			
            select.find('option').each(function(i){
                var option = $(this);
		
                if(i==select.attr('selectedIndex')){
                    selectBox.html(option.text());
                }
				
				
                // As of jQuery 1.4.3 we can access HTML5
                // data attributes with the data() method.
				
                if(option.data('skip')){
                    return true;
                }
				
                // Creating a dropdown item according to the
                // data-icon and data-html-text HTML5 attributes:
				
                var li = options.render(option);

                li.click(function(){
                    var current_app_value = option.val();
                    selectBox.html(option.text());
                    dropDown.trigger('hide');
					
                    // When a click occurs, we are also reflecting
                    // the change on the original select element:
                    select.val(option.val());
                    showSelect(current_app_value);
					
                    return false;
                });
		
                dropDown.append(li);
            });
			
            selectBoxContainer.append(dropDown.hide());
            select.hide().after(selectBoxContainer);
			
            // Binding custom show and hide events on the dropDown:
			
            dropDown.bind('show',function(){
				
                if(dropDown.is(':animated')){
                    return false;
                }
				
                selectBox.addClass('expanded');
                dropDown.slideDown();
				
            }).bind('hide',function(){
				
                if(dropDown.is(':animated')){
                    return false;
                }
				
                selectBox.removeClass('expanded');
                dropDown.slideUp();
				
            }).bind('toggle',function(){
                if(selectBox.hasClass('expanded')){
                    dropDown.trigger('hide');
                }
                else dropDown.trigger('show');
            });
			
            selectBox.click(function(){
                dropDown.trigger('toggle');
                return false;
            });
		
            // If we click anywhere on the page, while the
            // dropdown is shown, it is going to be hidden:
			
            $(document).click(function(){
                dropDown.trigger('hide');
            });

        });
    }
	
})(jQuery);*/


/* 
*  title:   about <table> 
*  rely:    jquery.tablesorter 
*/

// tr hovev's color
function tr_hover(obj, hover_css)
{
  obj.mouseover(function() {
    $(this).addClass(hover_css);
  });
  obj.mouseout(function() {
    $(this).removeClass(hover_css);
  });
}

tr_hover($(".new_silver_table tr"), "current");

//sort table
function table_sort(table_obj, hover_css)
{
  var getOrderNumber = function(node){
    return $.trim(node.innerHTML.split('/')[0]);
  }
  if(!hover_css)
  {
    hover_css = "tr_hover";
  }
  table_obj.tablesorter({textExtraction: getOrderNumber});
  table_obj.find("tr th").bind("click", function() {
    $("td." + hover_css).removeClass(hover_css);
    var tt = $(this)[0].title;
    $("td." + tt).addClass(hover_css);
  });
}


/* 
*  title:   about pop up dialog 
*  rely:    jquery.blockUI 
*/

//pop a dialog and block the page
function pop_dialog(msg, width, height, left, top)
{
    var height_page = $(window).height();
    var width_page = $(document).width();

    if(!left)
    {
        left= width_page/2 - msg.width()/2;
    }
    if(!top)
    {
        top=height_page/2 - (msg.height() / 2);
    }
    $.blockUI({
      css: {'color': '#cccccc','border':'0','width':width, 'height':height, 'left':left, 'top':top, background:'none',padding:'0px', 'textAlign':'left'},
      message: msg
    });
}
function adjustMsg() {
    var body = $('.new_popbox:visible');
    $("body>.blockMsg").css("top", $(window).height()/2 - (body.height() / 2) + "px");
}
$(window).resize(function(){
    adjustMsg();
});
$(function(){
    $(".tg_rss").click(function() {
        setTimeout($.unblockUI, 50);
    });
});


/* 
*  title:   about date input and handle
*  rely:    jquery.tools 
*/

// date input localization
$.tools.dateinput.localize("zh_cn",  {
    months:         '一月,二月,三月,四月, 五月,六月,七月,八月,九月,十月,十一月,十二月',
    shortMonths:   '一,二,三,四,五,六,七,八,九,十,十一,十二',
    days:          '星期日,星期一,星期二,星期三,星期四,星期五,星期六',
    shortDays:     '日,一,二,三,四,五,六'
 });

$(function(){
  $(":date").dateinput({lang: 'zh_cn', format: 'yyyy-mm-dd',selectors: true,firstDay:0});
});
 


/*
 *
 * Purpose: Ajax Loading Chart
 * Rely on: jquery.highcharts
 *
 **/

var cached_charts = {};
function render_chart(chart_id, title, data_src_url, params, force_reload, opts){

    var common_opts = {
        chart: {
            defaultSeriesType: "spline",
            animation: false
        },
        yAxis: {
            title:"",
            min:0
        },
        credits: {
            "enabled":false
        },
        plotOptions: {
            "area":{
                "stacking":null
            },
            "series":{
                animation: false,
                events: {
                  legendItemClick: function(event) {
                    var legendName = this.name+'_<dot>';
                    var tempSeries = this.chart.series;
                    var seriesLength = tempSeries.length;
                    for (var i=0; i < seriesLength; i++){
                      if (tempSeries[i].name == legendName){
                        tempSeries[i].visible ? tempSeries[i].hide() : tempSeries[i].show();
                      }
                    }
                  }
                }
            }
        },
        tooltip: {
            enabled: true,
            formatter: function() {
                return ''+
                this.x + '日'+ this.series.name + ' : '+ this.y;
            }
        },
        legend: {
            margin: 25,
            enabled: true
        },
        subtitle: {}
    };
    
    // Set Cached Chart Unique Id
    var chart_cache_id = 'umeng_' + chart_id;
    $.each(params, function(i,n){
        chart_cache_id += '_' + i + ':' + n;
    });

    // Do Nothing If Chart Existing and No Need To Reload
    var cached_data = $('#'+chart_id).data(chart_cache_id);
    if ( cached_charts[chart_cache_id] != undefined && !force_reload && cached_data != null ){
        try{
            cached_charts[chart_cache_id].destroy();
            cached_charts[chart_cache_id] = new Highcharts.Chart($.extend(true, {}, common_opts, cached_data));

            // Trigger chart_data_loaded event
            var data_source = $('#'+chart_id);
            data_source.trigger('chart_data_loaded', data_source.data(chart_cache_id+'_rawdata'));
        }catch(error){}
        return;
    }

    // Loading Data
    var categories = [];
    var series = [];
    var chart_canvas = $('#'+chart_id);
    var loading_img = $("<img src='/images/ajax-loader.gif'/>");
    chart_canvas.block({
        message: loading_img,
        css:{
            width:'32px',
            border:'none',
            background: 'none'
        },
        overlayCSS:{
            backgroundColor: '#FFF',
            opacity: 0.8
        },
        baseZ:997
    });
    $.get( data_src_url, params, function(resp){
        if( resp.result == 'success'){
            $.each(resp.dates, function(i,date){
                categories[i] = date
            });
            
            $.each(resp.stats, function(i,stat){
                series[i] = $.extend({visible:true}, stat);
            });
           
            // Set Init Options
            var options = $.extend(true, {
                chart: {
                    renderTo: chart_id
                },
                title: {
                    text: title
                },
                xAxis: {
                    categories: categories,
                    labels:{
                        align:"right",
                        //rotation:-45,
                        step: parseInt(categories.length / 7)
                    }
                },
                series: series
            }, opts || {});

            // Cache data
            $('#'+chart_id).data(chart_cache_id, options );
            $('#'+chart_id).data(chart_cache_id+'_rawdata', resp);

            // Destroy Existing Chart
            if ( cached_charts[chart_cache_id] != undefined ){
                try{
                    cached_charts[chart_cache_id].destroy();
                }catch(error){}
            }

            // Create Chart
            cached_charts[chart_cache_id] = new Highcharts.Chart($.extend(true, {}, common_opts, options));

            // Trigger chart_data_loaded event
            $('#'+chart_id).trigger('chart_data_loaded', resp);
        }
        chart_canvas.unblock();
    });
}
function flush_chart(){
  cached_charts = {};
}



$(document).ready(function(){
  $('a#login_testin').click(function() {
    $.ajax({
      type: 'post',
      url: '/users/logon_testin.json',
      error: function(data) {
        alert('请重新登录');
        window.location.href = '/users/sign_in';
      },
      success: function(data){
        var status = data['status'];
        if(status == 200){
          window.location.href = data['callback_url'];
        } else {
          alert('无法连接');
        }
      }
    });

    return false;
  });
});
